package cn.jingyuan.swan.system.web.config;

import cn.jingyuan.swan.cloud.oauth2.DefaultOAuth2Helper;
import cn.jingyuan.swan.cloud.oauth2.DefaultOAuth2ResourceDetails;
import cn.jingyuan.swan.cloud.oauth2.client.DefaultOAuth2ClientProperties;
import cn.jingyuan.swan.cloud.oauth2.error.DefaultOAuth2AccessDeniedHandler;
import cn.jingyuan.swan.cloud.oauth2.error.DefaultOAuth2AuthenticationEntryPoint;
import org.springframework.boot.actuate.autoconfigure.security.servlet.EndpointRequest;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;

import javax.annotation.Resource;

/**
 * 资源服务器配置
 */
@Configuration
@EnableResourceServer
@EnableConfigurationProperties({DefaultOAuth2ResourceDetails.class, DefaultOAuth2ClientProperties.class})
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Resource
    DefaultOAuth2ResourceDetails oAuth2ResourceDetails;

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        // 构建自定义远程 Token 服务类
        resources
            .tokenServices(DefaultOAuth2Helper.buildRemoteTokenServices(oAuth2ResourceDetails))
            .accessDeniedHandler(new DefaultOAuth2AccessDeniedHandler())
            .authenticationEntryPoint(new DefaultOAuth2AuthenticationEntryPoint());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf()
            .disable();

        http.cors()
            .disable();

        http.sessionManagement()
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);

        http.authorizeRequests()
            // 指定监控可访问权限
            .requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll()

            .antMatchers("/").permitAll()


            .antMatchers("/gateway/refresh").permitAll()


            .antMatchers("/app/{appId}/info").permitAll()
            .antMatchers("/app/client/{clientId}/info").permitAll()


            .antMatchers("/route/routes").permitAll()


            .antMatchers("/authority/access").permitAll()


            .anyRequest().authenticated();
    }

}

